package api

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"strconv"
	"sync"
	jwtRequest "week_one/client/vender/jwt"
)

type Message struct {
	FriendId string `json:"friend"`
	Content  string `json:"content"`
}
type Node struct {
	Conn *websocket.Conn
	Data chan []byte
}

var (
	ClientMap map[string]*Node
	wg        sync.WaitGroup
)

func Im(ctx *gin.Context) {
	claims, _ := ctx.Get("claims")
	id := claims.(*jwtRequest.ClaimsToken).Id
	userid := strconv.Itoa(int(id))
	upgrader := websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
	conn, err := upgrader.Upgrade(ctx.Writer, ctx.Request, nil)
	if err != nil {
		panic(err)
	}
	node := &Node{
		Conn: conn,
		Data: make(chan []byte, 50),
	}
	//ClientMap[userid] = nod
	log.Println(userid)
	wg.Add(2)
	go SendMsg(node)
	go ReadMsg(node)
	wg.Wait()
}
func SendMsg(node *Node) {
	defer wg.Done()
	for {
		_, message, err := node.Conn.ReadMessage()
		if err != nil {
			return
		}
		var msg Message
		json.Unmarshal(message, &msg)
		FriendMap, ok := ClientMap[msg.FriendId]
		if ok {
			FriendMap.Data <- []byte(msg.Content)
		}
	}
}
func ReadMsg(node *Node) {
	defer wg.Done()
	for {
		select {
		case data := <-node.Data:
			err := node.Conn.WriteMessage(websocket.TextMessage, data)
			if err != nil {
				return
			}
		}
	}
}
